package entities;

import force.Force;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.Point2D;
import java.util.List;
import main.Simulation;


/**
 * 
 * @author Robert C. Duvall
 * @author Paul
 * @author Lance
 */
public class Spring extends LineObject {

    private static final double NO_PAINT_TOLERANCE = 0.001;
    private double myK;

    /**
     * @param pointObject start mass attached
     * @param pointObject2 end mass attached
     * @param length equilibrium length of the spring
     * @param kVal spring constant
     */
    public Spring(PointObject pointObject, PointObject pointObject2,
            double length, double kVal) {
        super(pointObject, pointObject2, length);
        myK = kVal;
    }

    @Override
    public void update(Simulation canvas, double dt) {
        Point2D start = getStart().getCenter();
        Point2D end = getEnd().getCenter();
        double dx = start.getX() - end.getX();
        double dy = start.getY() - end.getY();

        // apply hooke's law to each attached mass
        Force f = new Force(Force.angleBetween(dx, dy), myK
                * (getLength() - Force.distanceBetween(dx, dy)));

        if (getStart() instanceof Mass) {
            Mass startMass = (Mass) getStart();
            startMass.applyForce(f);
        }

        f.negate();

        if (getEnd() instanceof Mass) {
            Mass endMass = (Mass) getEnd();
            endMass.applyForce(f);
        }
    }

    @Override
    public void chooseStyle(Graphics2D pen, int xStart, int yStart, int xEnd,
            int yEnd) {
        double dx = xStart - xEnd;
        double dy = yStart - yEnd;
        double len = Math.sqrt(dx * dx + dy * dy) - getLength();

        if (Math.abs(len) < NO_PAINT_TOLERANCE) {
            pen.setColor(Color.WHITE);
        }
        else if (len < 0.0) {
            pen.setColor(Color.BLUE);
        }
        else {
            pen.setColor(Color.RED);
        }

    }
}